<?php


namespace app\index\controller;


use app\common\controller\All;

class Explore extends All
{
    public function __construct()
    {
        parent::__construct();
    }

    public function m3u8()
    {
        if (request()->post()) {
            $data = input('post.');
            if ($data['id'] < 1) {
                $this->error('数据有误');
            }
            $vodInfo = db('vod')->where('vod_id', $data['id'])->field(
                'vod_id,vod_name,vod_time'
            )->find();
            if (empty($vodInfo)) {
                $this->error('没有找到该影片');
            }
            $exsitData = db('m3u8_setting')->where('vod_id', $data['id'])->find();
//                dump($vodInfo);
            if (empty($exsitData)) {
                //插入
                $insert = [
                    'time_added' => time(),
                    'vod_id' => $data['id'],
                    'delete_start_index' => $data['startIndex'],
                    'number' => $data['ts_number'],
                    'delete_end_index' => $data['ts_offset'],
                ];
                $insertId = db('m3u8_setting')->insertGetId($insert);
                if ($insertId < 1) {
                    $this->error('数据添加失败!');
                } else {
                    db('m3u8_job')->insert(
                        [
                            'vod_id' => $vodInfo['vod_id'],
                            'vod_time' => $vodInfo['vod_time'],
                            'time_added' => time(),
                            'status' => 0,
                            'need_delete' => 1
                        ]
                    );
                    db('vod')->where('vod_id', $vodInfo['vod_id'])->update(['is_cache' => 1]);
                    $this->error('数据添加成功！');
                }
            } else {
                //更新
                db('m3u8_setting')->where('vod_id', $data['id'])->update(
                    [
                        'delete_start_index' => $data['startIndex'],
                        'number' => $data['ts_number'],
                        'delete_end_index' => $data['ts_offset'],
                    ]
                );
                $this->success('更新成功！');
            }
        } else {
            $vod_id = input('id', 0, 'intval');
            if ($vod_id < 1) {
                $this->error('数据有误');
            }
            $vodInfo = db('vod')->where('vod_id', $vod_id)->field(
                'vod_id,vod_name,vod_play_from,vod_play_url'
            )->find();
            if (empty($vodInfo)) {
                $this->error('没有找到该影片');
            }
            //拆分并取得相应的数据
            $playFroms = explode('$$$', $vodInfo['vod_play_from']);

            $playUrlArray = [];
            $fromIndex = array_search('ckm3u8', $playFroms);
            if ($fromIndex !== false) {
                $from = 'ckm3u8';
            } else {
                $fromIndex = array_search('zuidam3u8', $playFroms);
                if ($fromIndex !== false) {
                    $from = 'zuidam3u8';
                }
            }
            // 返回空数据
            if (empty($from)) {
                return '没有找到可用的播放源';
            }
            $playUrlGroup = explode('$$$', $vodInfo['vod_play_url']);
            $playUrls = $playUrlGroup[$fromIndex];
            $playUrlsArray = explode('#', $playUrls);
            $playUrlArray = [];
            foreach ($playUrlsArray as $urlIndex => $playUrl) {
                list($key, $value) = explode('$', $playUrl);
                $playUrlArray = [
                    'key' => trim($key),
                    'value' => trim($value),
                    'from' => $from,
                    'vod_id' => $vodInfo['vod_id'],
                    'vod_name' => $vodInfo['vod_name'],
                ];
                break;
            }


            $m3u8content = file_get_contents($playUrlArray['value']);
            $urlArray = explode('/', $playUrlArray['value']);
            array_pop($urlArray);
            $m3u8contentArray = explode("\n", $m3u8content);
            $m3u8contentArray = array_filter($m3u8contentArray);
            $targetM3u8Url = array_pop($m3u8contentArray);
            $targetM3u8Url = join('/', $urlArray) . '/' . $targetM3u8Url;
            $m3u8content = file_get_contents($targetM3u8Url);
            $baseUrlArray = explode('/', $targetM3u8Url);
            array_pop($baseUrlArray);
            $baseUrl = join('/', $baseUrlArray);
            $m3u8contentArray = explode("\n", $m3u8content);
            $m3u8contentArray = array_filter($m3u8contentArray);
            $startIndex = -1;
            $m3u8contentArray = array_chunk($m3u8contentArray, 100);
            $m3u8contentArray = $m3u8contentArray[0];
            $duration = 0;
            foreach ($m3u8contentArray as $tsKey => $tsItem) {
                if (strpos($tsItem, '#EXTINF') === 0 && $startIndex === -1) {
                    $startIndex = $tsKey;
                }
                if (strpos($tsItem, '.ts') > 0 && (strpos(
                            $tsItem,
                            '#'
                        ) === false)) {
                    $m3u8contentArray[$tsKey] = $baseUrl . '/' . $tsItem;

                }else if(strpos($tsItem,'#EXTINF')===0){
                    $time =str_replace(['#EXTINF:',','],['',''],$tsItem);
                    $duration += $time;
                    $m3u8contentArray[$tsKey] = "当前ts播放完毕是[ ".$duration.' ]秒';
                }else{
                    unset($m3u8contentArray[$tsKey]);
                }


            }
            $info = [
                'id' => $vodInfo['vod_id'],
                'vod_name' => $vodInfo['vod_name'],
                'startIndex' => $startIndex
            ];
            $setting = db('m3u8_setting')->where('vod_id', $vodInfo['vod_id'])->find();
            if (!empty($setting)) {
                $info['ts_number'] = $setting['number'];
                $info['ts_offset'] = $setting['delete_end_index'];
            }
            $this->assign(
                'info',
                $info
            );
            $this->assign('m3u8contentArray', $m3u8contentArray);
            return $this->fetch('admin@explore/m3u8');
        }
    }

}